package com.glory.dgcpcpda.activity.mfg;


import android.content.Intent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.glory.dgcpcpda.adapter.StripIdListAdapter;

import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.dgcpcpda.R;
import com.glory.dgcpcpda.adapter.AddCarrierDataAdapter;
import com.glory.dgcpcpda.adapter.DefectListAdapter;
import com.glory.dgcpcpda.adapter.SuggestShelfListAdapter;
import com.glory.dgcpcpda.base.BaseActivity;
import com.glory.dgcpcpda.callback.CustomDialogEntityCallBack;
import com.glory.dgcpcpda.entity.DefectCodeEntity;
import com.glory.dgcpcpda.entity.LotInfoEntity;
import com.glory.dgcpcpda.entity.LotList;
import com.glory.dgcpcpda.entity.ScrapEntity;
import com.glory.dgcpcpda.entity.StripMappingEntity;
import com.glory.dgcpcpda.entity.response.BaseResponseBean;
import com.glory.dgcpcpda.utils.LotUtils;
import com.glory.dgcpcpda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_CommonCallback;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_TextCallback;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * FileName: DAWorkEndActivity
 * Author: XJH
 * Date: 2020/5/21 11:02
 * Description:DA工序结束作业
 * History:
 */
public class DAWorkEndActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.etTrackOutNum)
    TextView etTrackOutNum;
    @BindView(R.id.etBondUnit)
    TextView etBondUnit;
    @BindView(R.id.etIsTailOt)
    TextView etIsTailOt;
    @BindView(R.id.tvEqpWork)
    FreeUI_ClearEditText tvEqpWork;
    @BindView(R.id.tvStep)
    TextView tvStep;
    @BindView(R.id.etProjectNum)
    FreeUI_ClearEditText etProjectNum;
    @BindView(R.id.etMaterielModel)
    FreeUI_ClearEditText etMaterielModel;
    @BindView(R.id.tvMaterielModel)
    TextView tvMaterielModel;
    @BindView(R.id.rvMaterielModelList)
    RecyclerView rvMaterielModelList;
    @BindView(R.id.etMaterielBox)
    FreeUI_ClearEditText etMaterielBox;
    @BindView(R.id.rvMaterielBoxList)
    RecyclerView rvMaterielBoxList;
    @BindView(R.id.llBoxLayout)
    LinearLayout llBoxLayout;
    @BindView(R.id.tvDefectCode)
    TextView tvDefectCode;
    @BindView(R.id.ivDefectArrow)
    ImageView ivDefectArrow;
    @BindView(R.id.flDefectList)
    FrameLayout flDefectList;
    @BindView(R.id.rvDefectList)
    RecyclerView rvDefectList;
    @BindView(R.id.tvDefectNum)
    TextView tvDefectNum;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvLotState)
    TextView tvLotState;
    @BindView(R.id.tvSetTrackOutNum)
    TextView tvSetTrackOutNum;
    @BindView(R.id.etUserName)
    FreeUI_ClearEditText etUserName;
    @BindView(R.id.rvStripIdList)
    RecyclerView rvStripIdList;
    private SuggestShelfListAdapter suggestShelfListAdapter;
    private List<String> defectCodeList;
    private FreeUI_GeneralPop codePop;
    private DefectListAdapter defectListAdapter;
    private LotInfoEntity lotInfoEntity;
    private AddCarrierDataAdapter materielModelAdapter;
    private AddCarrierDataAdapter materielBoxAdapter;
    private StripIdListAdapter suggestListAdapter;
    private List<String> mDurablelist;
    //批次数量
    private String mainqty;
    private FreeUI_GeneralFragmentDialog scanDialog;
    private boolean Ischangeqty;
    private String isTailot;
    private int StripIDNum=0;//StripID料条数量
    private int ProjectNum=0;//MES返回框架条数
    private int isStripID=0;//判断是否校验领班权限

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_work_end_da;
    }

    @Override
    protected void initView() {
        setMainLayout(llMain);
        tvTitle.setText("结束作业");

        initRecyclerView(rvStripIdList,this);
        suggestListAdapter = new StripIdListAdapter(null);
        suggestListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        suggestListAdapter.isFirstOnly(true);
        rvStripIdList.setAdapter(suggestListAdapter);
        clear();

        defectCodeList = new ArrayList<>();
        initRecyclerView(rvMaterielModelList, this);
        initRecyclerView(rvMaterielBoxList, this);
        llBoxLayout.setVisibility(View.GONE);
        tvMaterielModel.setText("料框/料盒：");
        etMaterielModel.setHint("请扫描料框/料盒");
        //料框号列表
        materielModelAdapter = getCarrierAdapter();
        rvMaterielModelList.setAdapter(materielModelAdapter);
        //料盒号列表
        materielBoxAdapter = getCarrierAdapter();
        rvMaterielBoxList.setAdapter(materielBoxAdapter);
        //不良代码
        initRecyclerView(rvDefectList, this);
        defectListAdapter = new DefectListAdapter(null, tvDefectNum);
        defectListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        defectListAdapter.isFirstOnly(true);
        rvDefectList.setAdapter(defectListAdapter);

        initEdit(etLot, s -> {

            defectListAdapter.setNewData(null);
            tvDefectCode.setText("");
            tvDefectNum.setText("0");
            clear();

            LotUtils.searchLotInfo(DAWorkEndActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {

                @Override
                public void onSuccess(LotInfoEntity response) {
                    lotInfoEntity = response;
                    tvTitle.setText("结束作业" + "(" + response.getLOT().getSTEPDESC() + ")");

                    String state = response.getLOT().getSTATE();
                    if(state.equals("正在作业")){
                        state = state + " - " + response.getLOT().getEQUIPMENTID();
                    }
                    tvLotState.setText(state);

                    mainqty = response.getLOT().getMAINQTY();
                    etTrackOutNum.setText(mainqty);
                    String isTailot=response.getISTAILOT();
                    if(StringUtils.isNotEmpty(isTailot)){
                        isTailot=isTailot.equals("Y")?"是":"否";
                    }
                    etIsTailOt.setText(isTailot);
                    etBondUnit.setText("");
                    defectListAdapter.setTotalNum(Integer.parseInt(response.getLOT().getMAINQTY()));
                   // tvEqpWork.setText(response.getLOT().getEQUIPMENTID());
                    tvStep.setText(response.getLOT().getSTEPNAME() + "/" + response.getLOT().getSTEPDESC());
                    etProjectNum.setText(String.valueOf(response.getPACKAGETYPEQTY()));
                    ProjectNum=response.getPACKAGETYPEQTY();
                    mDurablelist = response.getDURABLELIST();
//                    materielModelAdapter.setNewData(mDurablelist);
                    if (response.getLOT().getCOMCLASS().equals("SCHD") ){
                        showConfirmDialog("该批次未投产，不允许此操作");
                    }else if(response.getLOT().getCOMCLASS().equals("COM")){
                        showConfirmDialog("该批次已被终止，不允许此操作");
                    }
                    else {
                        getDefectInfo(s);
                    }
                }

                @Override
                public void onFail(Throwable t) {
                    loadError(t, "LOTQUERY");
                }
            });

        });

        //输入设备获取设备实际生产数量
        initEdit(tvEqpWork,s->{
            if(!getText(tvEqpWork).equals(lotInfoEntity.getLOT().getEQUIPMENTID())){
                showToast("扫描的设备与该批次作业的设备不一致，请确认！",false);
                return;
            }

            clear();
            getStripMappingData(s);

            FreeUI_EntityCallBack<BaseResponseBean<JsonObject>> callback = new FreeUI_DialogEntityCallBack<BaseResponseBean<JsonObject>>
                    (new TypeToken<BaseResponseBean<JsonObject>>() {
                    }.getType(), getSupportFragmentManager(), this) {

                @Override
                public void onSuccess(Response<BaseResponseBean<JsonObject>> response) {
                    super.onSuccess(response);
                    if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                       String BondUnit=response.body().getResponse().getBody().get("BondUnit").toString();
                        etBondUnit.setText(BondUnit);
                    }
                }
                @Override
                public void onError(Response<BaseResponseBean<JsonObject>> response) {
                    super.onError(response);
                }
            };
            JsonObject map = new JsonObject();
            map.addProperty("EqpID", getText(tvEqpWork));
            map.addProperty("LotId", getText(etLot));
           NetUtils.requestPostNet("", "GetEQPBondUnit", this, map, callback);
        });

        initEdit(etMaterielModel, s -> {
            if (mDurablelist == null){
                showToast("请先扫描批次号!", false);
                return;
            }

            if (materielModelAdapter.getData().contains(s)) {
                showToast("当前载具已添加到载具列表中", false);
                return;
            }

            materielModelAdapter.getData().add(s);
            materielModelAdapter.notifyDataSetChanged();
            etMaterielModel.setText("");
        });

        initEdit(etMaterielBox, s -> {
            if (mDurablelist == null){
                showToast("请先扫描批次号!", false);
                return;
            }

            if (materielBoxAdapter.getData().contains(s)) {
                showToast("当前载具已添加到载具列表中", false);
                return;
            }

            materielBoxAdapter.getData().add(s);
            materielBoxAdapter.notifyDataSetChanged();
            etMaterielBox.setText("");
        });
    }

    private void getDefectInfo(String s) {

        FreeUI_EntityCallBack<BaseResponseBean<DefectCodeEntity>> callback = new FreeUI_DialogEntityCallBack<BaseResponseBean<DefectCodeEntity>>
                (new TypeToken<BaseResponseBean<DefectCodeEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<DefectCodeEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    defectCodeList.clear();
                    List<DefectCodeEntity.DefectCode> scrapcodelists = response.body().getResponse().getBody().getSCRAPCODELISTS();
                    for (DefectCodeEntity.DefectCode code : scrapcodelists){
                        defectCodeList.add(code.getKEYID() + "/" + code.getDESCRIPTION());
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<DefectCodeEntity>> response) {
                super.onError(response);
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", "BYLOT");
        map.add("LOT", new JsonParser().parse(new Gson().toJson(new LotList(s))).getAsJsonObject());//传批次集合
        NetUtils.requestPostNet("MES.GETSTEPBYLOT", "GETSTEPBYLOT", this, map, callback);
    }

    @Override
    protected void initData() {
        Ischangeqty = false;
    }

    private void Holdlot(String lotid){
        FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<JSONObject>>
                (new TypeToken<BaseResponseBean<JSONObject>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
                    showConfirmDialog(DAWorkEndActivity.this,"MAP芯片，如果改数了，默认自动HOLD，等待QC确认解扣！");
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<JSONObject>> response) {
                super.onError(response);
                loadError(response.getException(),"MES.LOTHOLD");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("LOTID",lotid);
        map.addProperty("ACTIONTYPE","HOLD");
        map.addProperty("ACTIONCODE","WAFERMAP_HOLD");
        map.addProperty("ACTIONREASON","WAFERMAP_HOLD");
        map.addProperty("ACTIONCOMMENT","Wafermap_modify_qty_auto_hold!");
        map.addProperty("ACTIONOWNER","ChangeNumber_QC");
        NetUtils.requestPostNet("MES.LOTHOLD","TRANSFERMES",this, map, callBack);
    }

    private void getStripMappingData(String eqpID) {
        FreeUI_EntityCallBack<BaseResponseBean<StripMappingEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<StripMappingEntity>>
                (new TypeToken<BaseResponseBean<StripMappingEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<StripMappingEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                    ArrayList<String> list=response.body().getResponse().getBody().getStripId();
                    ArrayList<StripMappingEntity.MESBINCODES> mesbincodeslist=response.body().getResponse().getBody().getStripBadCode();
                    clear();
                    if(list.size()>0){
                        etBondUnit.setText(response.body().getResponse().getBody().getStripQty());
                        StripIDNum=list.size();
                        suggestListAdapter.setNewData(list);
                        isStripID=1;
                    }else {
                        isStripID=0;
                        return;
                    }
                    if(mesbincodeslist.size()>0){
                        if (defectCodeList.size() <= 0) {
                            showToast("未获取到不良代码列表", false);
                            return;
                        }
                        defectListAdapter.setNewData(null);
                        int tvNum = 0;
                        for(int i=0 ;i<mesbincodeslist.size();i++){
                            for (String code : defectCodeList){
                                if(code.split("/")[0].equals(mesbincodeslist.get(i).getMESBINCODE())){
                                    ScrapEntity scrapEntity = new ScrapEntity();
                                    scrapEntity.setACTIONCODE(code.split("/")[0]);
                                    scrapEntity.setACTIONREASON(code.split("/")[1]);
                                    scrapEntity.setLOTID(lotInfoEntity.getLOT().getLOTID());
                                    scrapEntity.setLOTRRN(lotInfoEntity.getLOT().getOBJECTRRN());
                                    scrapEntity.setMAINQTY(mesbincodeslist.get(i).getNUMBER());
                                    ScrapEntity.MainQTY mainQTY = new ScrapEntity.MainQTY(mesbincodeslist.get(i).getNUMBER());
                                    List<ScrapEntity.MainQTY> data = new ArrayList<>();
                                    data.add(mainQTY);
                                    scrapEntity.setQTYLIST(data);
                                    scrapEntity.setACTIONTYPE("Scrap");
                                    defectListAdapter.addData(scrapEntity);
                                    tvNum = tvNum + Integer.parseInt(mesbincodeslist.get(i).getNUMBER());
                                }
                            }
                        }
                        tvDefectNum.setText(Integer.toString(tvNum));
                    }
                }

            }

            @Override
            public void onError(Response<BaseResponseBean<StripMappingEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"GetStrimpMappingData");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("LOTID", getText(etLot));
        map.addProperty("CUSTOMERCODE", lotInfoEntity.getLOT().getCUSTOMERCODE());
        map.addProperty("ISXRAY", "0");
        map.addProperty("EQUIPMENTID",eqpID);
        NetUtils.requestPostNet("EAP.GetStrimpMappingData","GetStrimpMappingData",DAWorkEndActivity.this,map,callBack);
    }

    @OnClick({R.id.tvBaseSubmit, R.id.flDefectList,R.id.tvSetTrackOutNum})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvBaseSubmit:
                if (actionControl("Submit02")) {
                    return;
                }

                if(isStripID==1) {
                    if (ProjectNum != Integer.parseInt(etProjectNum.getText().toString())) {
                        //装片领班权限
                        if (actionControl1("Submit39")) {
                            return;
                        }
                    }
                }

                if(StripIDNum!=0){
                    if(StripIDNum!=Integer.parseInt(etProjectNum.getText().toString())){
                        showToast("框架条数:"+Integer.parseInt(etProjectNum.getText().toString())+"与StripId条数:"+StripIDNum+"不一致，请检查！",false);
                        return;
                    }
                }

                if (getText(etLot).equals("")){
                    showToast("请先扫描批次信息",false);
                    return;
                }

                if (getText(etUserName).equals("")){
                    showToast("请输入工号",false);
                    return;
                }

                if (tvLotState.getText().toString().equals("待投产")){
                    showConfirmDialog("批次未投产，请联系计划部执行投产");
                    return;
                }

                if (tvLotState.getText().toString().equals("等待作业")){
                    showConfirmDialog("批次没有作业，请操作进站功能");
                    return;
                }
                if (getText(tvEqpWork).equals("")){
                    showToast("设备编号不能为空！",false);
                    return;
                }
                List<String> data = materielModelAdapter.getData();
                if (data.size() <= 0){
                    showToast("出站请绑定载具号",false);
                    return;
                }

                if(!getText(tvEqpWork).equals(lotInfoEntity.getLOT().getEQUIPMENTID())){
                    showToast("进出站设备不一致，不允许出站！",false);
                    return;
                }
                int defectNum = 0;
                if (!tvDefectNum.getText().toString().equals("")){
                    defectNum = Integer.parseInt(tvDefectNum.getText().toString());
                }

                List<String> dataBox = materielBoxAdapter.getData();
                data.addAll(dataBox);
                LotUtils.lotDATrackOut(this, getSupportFragmentManager(), getText(etUserName),getText(tvEqpWork),
                        getText(etLot), defectListAdapter.getData(), data, lotInfoEntity,
                        tvDefectNum.getText().toString().equals("") ? 0 : Integer.parseInt(tvDefectNum.getText().toString()),
                        String.valueOf(Integer.parseInt(etTrackOutNum.getText().toString()) - defectNum)
                        ,"DefaultTrackOut", new LotUtils.netCallback() {
                            @Override
                            public void onSuccess(Object response) {
                                StripIDNum=0;
                                ProjectNum=0;
                                isStripID=0;
                                finish();

/*
                                // 是MAP上芯 并且改数了
                                if(lotInfoEntity.getCORELOADINGMODE().equals("MAP芯片") && Ischangeqty){
                                    // 把这个值 给改为false 避免下次 不需要HOLD的，
                                    Ischangeqty = false;
                                    Holdlot(getText(etLot));
                                }else {
                                    finish();
                                }*/
                            }

                            @Override
                            public void onFail(Throwable t) {
//                                if (!tvDefectNum.getText().toString().equals("")){
//                                    int defectNum = Integer.parseInt(tvDefectNum.getText().toString());
//                                    etTrackOutNum.setText(String.valueOf(Integer.parseInt(etTrackOutNum.getText().toString()) + defectNum));
//                                }
                            }
                        });
                break;
            case R.id.flDefectList:
                if (defectCodeList.size() <= 0) {
                    showToast("未获取到不良代码列表", false);
                    return;
                }

                if (codePop != null) {
                    if (codePop.isShowing()) {
                        codePop.dismiss();
                    }
                } else {
                    codePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flDefectList.getWidth(), defectCodeList, ivDefectArrow, (codeS, i) -> {
                        tvDefectCode.setText(codeS.split("/")[0]);
                        ScrapEntity scrapEntity = new ScrapEntity();
                        scrapEntity.setACTIONCODE(codeS.split("/")[0]);
                        scrapEntity.setACTIONREASON(codeS.split("/")[1]);
                        scrapEntity.setLOTID(lotInfoEntity.getLOT().getLOTID());
                        scrapEntity.setLOTRRN(lotInfoEntity.getLOT().getOBJECTRRN());
                        scrapEntity.setACTIONTYPE("Scrap");

                        if (defectListAdapter.getData().size() > 0) {
                            if (containCode(scrapEntity)) {
                                defectListAdapter.addData(scrapEntity);
                            }
                        } else {
                            defectListAdapter.addData(scrapEntity);
                        }

                    });
                }
                FreeApi_PopUtils.setArrowShow(ivDefectArrow);
                codePop.showAsDropDown(flDefectList, 0, 0);
                break;
            case R.id.tvSetTrackOutNum:
                if(lotInfoEntity == null){
                    showToast("请先扫描批次信息！",false);
                    return;
                }

                scanDialog = FreeApi_DialogUtils.getScanDialog(this, "请输入出站数量", new FreeUI_TextCallback() {
                    @Override
                    public void onSuccess(String s) {
                        try {
                            int inputMainQty = Integer.parseInt(s);
                            int mainQty = Integer.parseInt(mainqty);
                            if (inputMainQty < mainQty){
                                showToast("出站数量不能调小",false);
                                return;
                            }

                            etTrackOutNum.setText(s);
                            // 判断是否修改了 数值
                            Ischangeqty = true;
                            scanDialog.dismiss();
                        }catch (NumberFormatException e){
                            e.printStackTrace();
                            showToast("请输入数字",false);
                        }

                    }
                });
                scanDialog.show(getSupportFragmentManager(),"SET_TEACKOUT_NUM");
                break;
        }

    }

    private boolean containCode(ScrapEntity scrapEntity) {
        for (ScrapEntity bean : defectListAdapter.getData()) {
            if (bean.getACTIONCODE().equals(scrapEntity.getACTIONCODE())) {
                showToast("列表中已有当前不良代码!", false);
                return false;
            }
        }
        return true;
    }

    private void clear(){
        suggestListAdapter.getData().clear();
        suggestListAdapter.notifyDataSetChanged();
    }
}